package com.health.institution.service.impl;

import java.time.Duration;
import java.util.List;
import java.util.ArrayList;

import com.health.common.utils.MinIOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.health.common.utils.DateUtils;
import com.health.institution.mapper.MedicalHospitalMapper;
import com.health.institution.mapper.DepartmentMapper;
import com.health.institution.domain.MedicalHospital;
import com.health.institution.domain.Department;
import com.health.institution.service.IMedicalHospitalService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 机构管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-27
 */
@Service
public class MedicalHospitalServiceImpl implements IMedicalHospitalService {
    @Autowired
    private MedicalHospitalMapper medicalHospitalMapper;

    @Autowired
    private DepartmentMapper departmentMapper;


    /**
     * 查询机构管理
     *
     * @param hospitalId 机构管理主键
     * @return 机构管理
     */
    @Override
    public MedicalHospital selectMedicalHospitalByHospitalId(Long hospitalId) {
        return medicalHospitalMapper.selectMedicalHospitalByHospitalId(hospitalId);
    }

    /**
     * 查询机构管理列表
     *
     * @param medicalHospital 机构管理
     * @return 机构管理
     */
    @Override
    public List<MedicalHospital> selectMedicalHospitalList(MedicalHospital medicalHospital) {
        return medicalHospitalMapper.selectMedicalHospitalList(medicalHospital);
    }

    /**
     * 新增机构管理
     *
     * @param medicalHospital 机构管理
     * @return 结果
     */
    @Override
    public int insertMedicalHospital(MedicalHospital medicalHospital) {
        medicalHospital.setCreateTime(DateUtils.getNowDate());
        return medicalHospitalMapper.insertMedicalHospital(medicalHospital);
    }

    /**
     * 修改机构管理
     *
     * @param medicalHospital 机构管理
     * @return 结果
     */
    @Override
    public int updateMedicalHospital(MedicalHospital medicalHospital) {
        medicalHospital.setUpdateTime(DateUtils.getNowDate());
        return medicalHospitalMapper.updateMedicalHospital(medicalHospital);
    }

    /**
     * 批量删除机构管理
     *
     * @param hospitalIds 需要删除的机构管理主键
     * @return 结果
     */
    @Override
    public int deleteMedicalHospitalByHospitalIds(Long[] hospitalIds) {
        return medicalHospitalMapper.deleteMedicalHospitalByHospitalIds(hospitalIds);
    }

    /**
     * 删除机构管理信息
     *
     * @param hospitalId 机构管理主键
     * @return 结果
     */
    @Override
    public int deleteMedicalHospitalByHospitalId(Long hospitalId) {
        return medicalHospitalMapper.deleteMedicalHospitalByHospitalId(hospitalId);
    }

    /**
     * 查询机构管理详情（包含科室信息）
     */
    @Override
    public MedicalHospital selectMedicalHospitalWithDepartments(Long hospitalId) {
        // 直接查询机构基本信息，不区分状态
        MedicalHospital hospital = medicalHospitalMapper.selectMedicalHospitalByHospitalId(hospitalId);
        if (hospital == null) {
            return null; // 机构不存在
        }
        // 获取关联的科室ID列表
        List<Long> departmentIds = medicalHospitalMapper.selectDepartmentIdsByHospitalId(hospitalId);
        hospital.setDepartmentIds(departmentIds);

        // 获取关联的科室详细信息
        List<Department> departments = departmentMapper.selectDepartmentsByHospitalId(hospitalId);
        hospital.setDepartments(departments);

        // 分离一级科室和二级科室（只有在有关联科室时才处理）
        if (departments != null && !departments.isEmpty()) {
            List<Department> primaryDepartments = new ArrayList<>();
            List<Department> secondaryDepartments = new ArrayList<>();
            for (Department dept : departments) {
                if (dept.getParentId() == 0 || dept.getParentId() == null) {
                    primaryDepartments.add(dept);
                } else {
                    secondaryDepartments.add(dept);
                }
            }
            hospital.setPrimaryDepartments(primaryDepartments);
            hospital.setSecondaryDepartments(secondaryDepartments);
        }
        return hospital;
    }

    /**
     * 新增机构管理（包含科室关联）
     */
    @Override
    @Transactional
    public int insertMedicalHospitalWithDepartments(MedicalHospital medicalHospital) {
        medicalHospital.setCreateTime(DateUtils.getNowDate());
        int result = medicalHospitalMapper.insertMedicalHospital(medicalHospital);

        if (result > 0 && medicalHospital.getDepartmentIds() != null
                && !medicalHospital.getDepartmentIds().isEmpty()) {
            // 插入科室关联
            medicalHospitalMapper.insertHospitalDepartments(
                    medicalHospital.getHospitalId(), medicalHospital.getDepartmentIds());
        }
        return result;
    }

    /**
     * 修改机构管理（包含科室关联）
     */
    @Override
    @Transactional
    public int updateMedicalHospitalWithDepartments(MedicalHospital medicalHospital) {
        medicalHospital.setUpdateTime(DateUtils.getNowDate());
        int result = medicalHospitalMapper.updateMedicalHospital(medicalHospital);

        if (result > 0) {
            // 先删除原有关联
            medicalHospitalMapper.deleteHospitalDepartments(medicalHospital.getHospitalId());

            // 再插入新的关联
            if (medicalHospital.getDepartmentIds() != null
                    && !medicalHospital.getDepartmentIds().isEmpty()) {
                medicalHospitalMapper.insertHospitalDepartments(
                        medicalHospital.getHospitalId(), medicalHospital.getDepartmentIds());
            }
        }
        return result;
    }

    @Autowired
    private MinIOUtils minIOUtils;

    /**
     * 上传机构Logo
     */
    @Override
    public String uploadLogo(MultipartFile file, Long hospitalId) {
        String url;
        try {
            // 检查文件是否为空
            if (file == null || file.isEmpty()) {
                throw new RuntimeException("上传的文件为空");
            }

            if (file.getSize() == 0) {
                throw new RuntimeException("文件大小为0");
            }
            // 尝试上传
            System.out.println("调用MinIOUtils.uploadFile...");
            url = minIOUtils.uploadFile(file);
            System.out.println("上传成功，URL: " + url);
            // 查询数据库中老的Logo URL，若存在则删除
            MedicalHospital hospital = medicalHospitalMapper.selectMedicalHospitalByHospitalId(hospitalId);
            if (hospital != null && hospital.getLogo() != null && !hospital.getLogo().trim().isEmpty()) {
                try {
                    System.out.println("删除旧Logo: " + hospital.getLogo());
                    minIOUtils.deleteFile(hospital.getLogo());
                } catch (Exception e) {
                    // 删除旧文件失败不影响新文件上传，只记录日志
                    System.err.println("删除旧Logo失败: " + e.getMessage());
                }
            }
            // 将新Logo URL更新进数据库
            MedicalHospital updateHospital = new MedicalHospital();
            updateHospital.setHospitalId(hospitalId);
            updateHospital.setLogo(url);
            updateHospital.setUpdateTime(DateUtils.getNowDate());
            int updateResult = medicalHospitalMapper.updateMedicalHospital(updateHospital);
            System.out.println("数据库更新结果: " + updateResult);
            return url;
        } catch (Exception e) {
            System.err.println("Logo上传异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("机构Logo上传失败: " + e.getMessage());
        }
    }
}